//
//  AppDelegate.m
//  SnailPost
//
//  Created by 抠泥ser on 16/3/7.
//  Copyright © 2016年 抠泥ser. All rights reserved.
//

#import "AppDelegate.h"
#import "PrefixHeader.pch"
#import <TencentOpenAPI/TencentOAuth.h> // QQ登录 分享
#import "LeadViewController.h"

@interface AppDelegate ()

@property (nonatomic, strong) UIView *buttonView;/**< 按钮所在视图 */
@property (nonatomic, strong) UIButton *playButton;/**< 播放按钮 */
@property (nonatomic, strong) NSTimer *timer;/**< 计时器 */


@property (nonatomic, assign) BOOL isT;/**< 记录播放功能 */

@property (nonatomic, strong) UISlider *slider;/**< 记录时常 */

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    // 推送判断版本号
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0f) {
        
        [JPUSHService registerForRemoteNotificationTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound |UIUserNotificationTypeAlert categories:nil];
        
    }else{
        // 8.0 直接注册 的方法  registerForRemoteNotifications
        [JPUSHService registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert categories:nil];
    }
    [JPUSHService setupWithOption:launchOptions appKey:@"6bdba9872bd4cfbaee4c69b4" channel:nil apsForProduction:NO];
    
    // 延迟
    [NSThread sleepForTimeInterval:2.0];
    
    //获取夜间模式状态
    [ThemeManage shareThemeManage].isNight = [[NSUserDefaults standardUserDefaults] boolForKey:@"night"];
    _isT = YES;
    
    // 判断是否是第一次打开
    BOOL isFirst = [[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"];
    if (!isFirst) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        LeadViewController *yindaoyeVC = [[LeadViewController alloc] init];
        [self setTabBar];
        self.window.rootViewController = yindaoyeVC;
        
    } else {
        // 创建tabBar
        [self setTabBar];
        self.window.rootViewController = _tabBar;
    }
    
    
    
    
    //self.window.rootViewController = _tabBar;
    
    // 创建播放器
    [self setPlayMusic];
    
    return YES;
}


- (void)setPlayMusic
{
    NSString *str1 = @"http://fdfs.xmcdn.com/group14/M07/23/3C/wKgDY1bnxL3zB08tAB4mi6d_wTk763.mp3";
    //NSString *str2 = @"";
    //NSString *str3 = @"";
    NSArray *arr = [NSArray arrayWithObjects:str1, nil];
    self.playerManager = [PlayerManager defaultManager];
    self.playerManager.playerType = PlayTypeList;
    self.playerManager.musicArray = [NSMutableArray arrayWithArray:arr];
    [self.playerManager play];
}

- (void)setTabBar{
    // 新闻页
    NewsViewController *newsVC = [[NewsViewController alloc] init];
    UINavigationController *newsNavi = [[UINavigationController alloc] initWithRootViewController:newsVC];
    newsNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"新闻" image:[UIImage imageNamed:@"xinwen"] tag:1000];
//    [newsNavi.navigationBar NightWithType:UIViewColorTypeNormal];
    // 视频页
    VideoViewController *videoVC = [[VideoViewController alloc] init];
    UINavigationController *videoNavi = [[UINavigationController alloc] initWithRootViewController:videoVC];
    videoNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"视频" image:[UIImage imageNamed:@"video"] tag:1001];
//    [videoNavi.navigationBar NightWithType:UIViewColorTypeNormal];
    // 中间没有用的navigation
    UINavigationController *noNavi = [[UINavigationController alloc] init];
    noNavi.tabBarItem = [[UITabBarItem alloc] init];
    //view(遮挡住那个没用的VC)
    self.buttonView = [[UIView alloc] initWithFrame:CGRectMake((self.window.frame.size.width - 70) / 2, 49 - 70, 70, 70)];
    _buttonView.center = CGPointMake(self.window.center.x, _buttonView.center.y);
    _buttonView.backgroundColor = [UIColor colorWithRed:235 / 255.0 green:235 / 255.0 blue:241 / 255.0 alpha:1.0];
    _buttonView.layer.cornerRadius = 35;
    _buttonView.clipsToBounds = YES;
    
    //播放暂停按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playButton.frame = CGRectMake(5, 5,  60, 60);
    //_playButton.center = CGPointMake(self.window.center.x, _playButton.center.y);

   // _playButton.backgroundColor = [UIColor redColor];
    _playButton.layer.cornerRadius = 30;
    _playButton.clipsToBounds = YES;
    [_buttonView addSubview:_playButton];
    [_playButton addTarget:self action:@selector(playControl) forControlEvents:(UIControlEventTouchUpInside)];
    [_playButton setImage:[UIImage imageNamed:@"kr3d_04"] forState:(UIControlStateNormal)];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(xuanzhuan) userInfo:nil repeats:YES];
    
    // 创建通知  注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginPlay:) name:@"beginPlay" object:nil];
    // 创建暂停通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zan:) name:@"zan" object:nil];
    
    // 音乐页
    MusicViewController *musicVC = [[MusicViewController alloc] init];
    UINavigationController *musicNavi = [[UINavigationController alloc] initWithRootViewController:musicVC];
    musicNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"音乐" image:[UIImage imageNamed:@"yinle"] tag:1002];
//    [musicNavi.navigationBar NightWithType:UIViewColorTypeNormal];
    // 用户页
    UserViewController *userVC = [[UserViewController alloc] init];
    UINavigationController *userNavi = [[UINavigationController alloc] initWithRootViewController:userVC];
    userNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"我的" image:[UIImage imageNamed:@"person"] tag:1003];
//    [userNavi.navigationBar NightWithType:UIViewColorTypeNormal];
    // tabBar
    self.tabBar = [[UITabBarController alloc] init];
    _tabBar.viewControllers = @[newsNavi, videoNavi, noNavi, musicNavi, userNavi];
//    [_tabBar.tabBar NightWithType:UIViewColorTypeNormal];
    [self.tabBar.tabBar addSubview:_buttonView];
    
    
    
    self.slider = [[UISlider alloc] init];
    
}

- (void)zan:(NSNotification *)notification
{
    [self.timer invalidate];
}

#pragma mark - 控制播放器方法
- (void)playControl
{
    if (self.playerManager.playerState == PlayStatePlay) {
        [self.playerManager pause];
        [self.timer invalidate];
       // _playButton.backgroundColor = [UIColor goldColor];
        [self progressObserving];
    } else {
        [self.playerManager play];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(xuanzhuan) userInfo:nil repeats:YES];
      //  _playButton.backgroundColor = [UIColor redColor];
    }
//    _isT = !_isT;
}

#pragma mark - slider走方法
-(void)progressObserving{

//    __weak AppDelegate *app = self;
    [self.playerManager.avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //       VC.bofang.selected  = YES;
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        app.slider.value = app.playerManager.currentTime / app.playerManager.totalTime;
        
        if (app.slider.value == 1) {
            [app.playerManager playerDidFinish];
        }
        
        
    }];
}




#pragma mark - 获取图片通知
- (void)beginPlay: (NSNotification *)notification
{
    //self.playButton.backgroundColor = [UIColor clearColor];
    //[self.playButton setBackgroundImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:notification.object]]] forState:(UIControlStateNormal)];
    [self.playButton setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:notification.object]]] forState:(UIControlStateNormal)];
    
    [self.timer invalidate];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(xuanzhuan) userInfo:nil repeats:YES];
    
    
}

#pragma mark - 旋转
- (void)xuanzhuan
{
    self.playButton.transform = CGAffineTransformRotate(self.playButton.transform, M_1_PI - 0.3);
}

#pragma mark - 推送方法
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
    NSLog(@"~~%@", deviceToken);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
#pragma mark - 重写handleopenURL

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    // 腾讯
    return  [TencentOAuth HandleOpenURL:url];
}
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    // 腾讯
    return  [TencentOAuth HandleOpenURL:url];
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
